# encoding=utf8
import json
import os
import time
from resource_management import *
from elastic_env import elastic_env
from resource_management.libraries.functions.check_process_status import check_process_status

class Master(Script):

  def install(self, env):
    import params
    env.set_params(params)

    # 删除现有的软连接
    Execute('rm -rf /usr/hdp/current/elastic')

    Execute('rm -rf {0}/elastic*'.format(params.hdp_base_dir))
    # Download elasticsearch.tar.gz
    Execute('wget {0} -O elastic.tar.gz'.format(params.es_download_url))

    # Install Elasticsearch
    Execute('tar -zxvf elastic.tar.gz -C {0} && rm -rf elastic.tar.gz'.format(params.hdp_base_dir))


    Execute('mv {0}/elastic* {1}'.format(params.hdp_base_dir, params.elastic_base_dir))

    Execute('ln -s {0} /usr/hdp/current/elastic'.format(params.elastic_base_dir))

    # Remove Elasticsearch installation file
    Execute('rm -rf elasticsearch.tar.gz')

    Logger.info("Install complete")

    self.configure(env)

  def stop(self, env):
    import params
    env.set_params(params)
    # Stop Elasticsearch
    Execute('ps -ef | grep elastic/config | grep -v grep |awk \'{print $2}\' | xargs kill -9',
            user=params.elastic_user,
            ignore_failures=True
            )
    # 删除pid文件
    File([params.elastic_pid_file],
         action="delete")

    Logger.info("Stop complete!")
    time.sleep(5)

  def start(self, env):
    import params
    env.set_params(params)
    # Configure Elasticsearch
    self.configure(env)

    # Start Elasticsearch
    # -p 将pid生成到指定的pid文件
    cmd = format("{elastic_base_dir}/bin/elasticsearch -d -p {elastic_pid_file}")
    Execute(cmd, user=params.elastic_user)

    # get Elasticsearch pid and write filex
    Execute(
      'ps -ef | grep elasticsearch/config | grep -v grep | awk \'{print $2}\' > ' + params.elastic_pid_file,
      user=params.elastic_user
    )

    params_data = {
      "es": {
        "ip": params.elasticsearch_service_hosts,
        "port": params.elasticsearch_port,
        "pid_file": params.elastic_pid_file,
        "log_dir": params.elastic_log_dir
      }
    }
    Logger.info("params_data: {0}".format(json.dumps(params_data)))
    current_dir = os.path.dirname(os.path.abspath(__file__))
    # cmd = "nohup /usr/bin/python -u {0}/es_metrics.py '{1}'  > /dev/null 2>&1 &".format(current_dir,
    #                                                                                     json.dumps(params_data))
    # Execute(cmd, user=params.elastic_user)

  def status(self, env):
    import status_params
    env.set_params(status_params)
    check_process_status(status_params.elastic_pid_file)

  def configure(self, env):
    # Import peoperties defined in -config.xml file from the params class
    import params
    # This allows us to access the params.elastic_pid_file property as
    # format('{elastic_pid_file}')
    params.pika_slave = True
    env.set_params(params)
    elastic_env('master_node')

if __name__ == "__main__":
  Master().execute()